﻿using DAEProde.Domain;
using DAEProde.Tasks.ViewModels;
using SharpLite.Domain.DataInterfaces;
using System.Linq;
using System;
using DAEProde.Domain.Validators;

namespace DAEProde.Tasks
{
    public class TournamentCudTasks : BaseEntityCudTasks<Tournament, EditTournamentViewModel>
    {
        private readonly IRepository<Team> _teamRepository;
        private readonly IRepository<Tournament> _tournamentRepository;

        public TournamentCudTasks(IRepository<Tournament> tournamentRepository, IRepository<Team> teamRepository)
            : base(tournamentRepository) { _tournamentRepository = tournamentRepository;  _teamRepository = teamRepository; }

        protected override void TransferFormValuesTo(Tournament toUpdate, Tournament fromForm)
        {
            toUpdate.Name = fromForm.Name;           
        }

        public virtual ActionConfirmation<Tournament> SaveTeams(Tournament fromForm)
        {
            if (fromForm == null) throw new ArgumentNullException("fromForm may not be null");
            if (!DataAnnotationsValidator.TryValidate(fromForm)) throw new InvalidOperationException("fromForm is in an invalid state");


            // But if the ID of fromForm is > 0, then we know we're updating an existing one.
            // Always update the existing one instead of simply "updating" the item from the form.  Otherwise,
            // you risk the loss of important data, such as references not captured by the form or audit 
            // details that exists from when the object was initially saved.
            Tournament toUpdate = _tournamentRepository.Get(fromForm.Id);

            toUpdate.Teams.Clear();

            foreach (var team in fromForm.Teams)
            {
                toUpdate.Teams.Add(team);
            }

            // Since any changes will be automatically persisted to the DB when the current transaction
            // is committed, we want to make sure it's in a valid state after being updated.  If it's 
            // not, it's most likely a development bug. In design-by-contract speak, this is an "ensure check."
            if (!DataAnnotationsValidator.TryValidate(toUpdate))
                throw new InvalidOperationException("The " + GetFriendlyNameOfType() + " could not be updated due to missing or invalid information");

            return ActionConfirmation<Tournament>.CreateSuccessConfirmation(
                "The " + GetFriendlyNameOfType() + " was successfully updated.", fromForm);
        }

        // Construccion basica del view model que inicializa lista de equipos
        public override EditTournamentViewModel CreateEditViewModel()
        {
            var viewModel = base.CreateEditViewModel();

            // Esto sera mostrado por la vista para seleccionar equipos
            viewModel.AvaileableTeams = _teamRepository.GetAll().OrderBy(pc => pc.Name);

            return viewModel;
        }
    }
}
